#include "util.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <cstring>
#include <string>
using namespace std;

inline int err_sys(const char* msg) {
    fprintf(stderr, "%s -- %s\n", msg, strerror(errno));
}

int Open(const char* filename, int flags) {
    int fd;
    if ((fd = open(filename, flags)) == -1)
        err_sys("Opening error");
    return fd;
}

void Close(int fd) {
    if (close(fd) == -1)
        err_sys("Close error");
}

int Pipe(int fd[]) {
    int r;
    if ((r = pipe(fd)) < 0)
        err_sys("Pipe error");
    return r;
}

vector<int> find_process_id(const char* name) {
    string command = "pgrep ";
    command += name;
    FILE* s = popen(command.c_str(), "r");
    if (s == NULL)
	err_sys("popen failed");

    static char buffer[50];
    vector<int> result;
    while (fgets(buffer, 50, s) != NULL) {
	result.push_back(atoi(buffer));
    }

    return result;
}
